<template>
  <a-form-model
    ref="formComp"
    :model="formData"
    :rules="rules"
    layout="horizontal"
    class="AsteriskAfter newEditStyle">
    <a-row :gutter="20">
      <a-col :md="24" :sm="24">
        <a-form-model-item prop="account">
          <template #label>
            <span style="margin-right:2px;">{{ $t('loginAccount') }}</span>
            <question-mark-tip :tip-title="$t('verifyAccountTip')" :popupContainer="getPopupContainer">
            </question-mark-tip>
          </template>
          <a-input v-model="formData.account" :disabled="Boolean(formData.id)"/>
        </a-form-model-item>
      </a-col>
    </a-row>
    <a-row :gutter="20">
      <a-col :md="24" :sm="24">
        <a-form-model-item prop="name">
          <template #label>
            <span style="margin-right:2px;">{{ $t('userName') }}</span>
            <question-mark-tip :tip-title="$t('verifyUserNameOrAccountTip')" :popupContainer="getPopupContainer">
            </question-mark-tip>
          </template>
          <a-input v-model="formData.name" :disabled="Boolean(formData.id)"/>
        </a-form-model-item>
      </a-col>
    </a-row>
    <a-row>
      <a-col :md="24" :sm="24">
        <a-form-model-item :label="$t('org')" prop="organizationId">
            <select-user-tree :organizationId="editRecord.organizationId" @select="selectTree"/>
          <!--<department-tree @select="selectTree" :selectedIds="formData.organizationIds" :selectedId="[formData.organizationId]" type="EditUser"></department-tree>-->
          <!--<a-cascader :placeholder="$t('pleaseSelect')" :options="treeData"-->
                      <!--:fieldNames="{label:'name',value:'id',children: 'childOrganizations'}"-->
                      <!--allowClear  v-model="formData.organizationId" change-on-select/>-->
        </a-form-model-item>
      </a-col>
    </a-row>
    <a-row>
      <a-col :md="24" :sm="24">
        <a-form-model-item :label="$t('role')" prop="roleIds">
          <role-select
            :default-value="formData.roleIds"
            @changerole="changeRole"
          ></role-select>
        </a-form-model-item>
      </a-col>
    </a-row>
    <a-row>
      <a-col :md="24" :sm="24">
        <a-form-model-item :label="$t('userEmail')" prop="email">
          <a-input v-model="formData.email"  :disabled="Boolean(formData.id)"/>
        </a-form-model-item>
      </a-col>
    </a-row>
    <a-row>
      <a-col :md="24" :sm="24">
        <a-form-model-item :label="$t('电话')" prop="phone">
          <a-input v-model="formData.phone"/>
        </a-form-model-item>
      </a-col>
    </a-row>
    <a-row>
      <a-col :md="24" :sm="24">
        <a-form-model-item :label="$t('remark')" prop="remark">
          <custom-text-area
            @change="formData.remark = $event"
            :val="formData.remark"
            :rows="5"
            :max-len="200"
          ></custom-text-area>
        </a-form-model-item>
      </a-col>
    </a-row>
  </a-form-model>
</template>
<script>
import tableEllipsis from '@/components/Ellipsis/TableEllipsis'
import RoleSelect from '@/views/components/RoleSelect'
import { mapState } from 'vuex'
import {checkEmail, checkIsPositiveInteger, checkTextLen,checkInputRightAccountTip} from '@/utils/validate'
import CustomTextArea from '@/components/CustomTextArea/index.vue'
import QuestionMarkTip from '@/views/components/QuestionMarkTip'
import DepartmentTree from './DepartmentTree'
import selectUserTree from './selectUserTree'
export default {
  name: 'NewEditModel',
  components: { tableEllipsis, RoleSelect, CustomTextArea, QuestionMarkTip, DepartmentTree, selectUserTree },
  props: {
    editRecord: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  computed: {
    ...mapState({
      roles: (state) => state.role.roleData,
      treeData: (state) => state.org.treeData,
    })
  },
  data () {
    const checkUserName = (rule, text, callback) => {
      const reg = /[^a-zA-Z0-9\u4E00-\u9fa5]/
      if (reg.test(text)) {
        callback(new Error(this.$t('verifyUserNameOrAccountTip')))
        return
      }
      callback()
    }
    return {
      formData: {
        id: '',
        account: '',
        email: '',
        name: '',
        organizationId: '',
        organizationIds: [],
        phone: '',
        remark: '',
        roleIds: []
      },
      rules: {
        account: [
          { required: true, message: this.$t('pleaseInput') },
          // { validator: checkInputRightAccountTip() },
          // { validator: checkTextLen(7) }
        ],
        name: [
          { required: true, message: this.$t('pleaseInput') },
          { validator: checkUserName },
          { validator: checkTextLen(20) }
        ],
        organizationIds: [
          { required: true, message: this.$t('pleaseSelect') }
        ],
        roleIds: [
          { required: true, message: this.$t('pleaseSelect') }
        ],
        // email: [
        //   { required: true, message: this.$t('pleaseInput') },
        //   {
        //     validator: (rule, value, callback) => {
        //       checkEmail(rule, value, callback)
        //     }
        //   },
        //   { validator: checkTextLen() }
        // ],
        remark: [
          { validator: checkTextLen(200) }
        ]
      },
      time: 1000
    }
  },
  watch: {
    editRecord: {
      handler (val) {
        this.resetFormData()
        this.$nextTick(() => {
          Object.keys(this.formData).forEach(key => {
            if (typeof val[key] !== 'undefined') {
              this.formData[key] = val[key]
            }
          })
          // if (!this.formData.organizationIds) {
            this.formData.organizationIds = [...this.getParentIdsById(this.treeData, this.formData.organizationId).reverse(), this.formData.organizationId]
          // }
        })
      },
      immediate: true
    }
  },

  methods: {
    selectTree(e){
      this.formData.organizationId = e
      // console.log(e)
    },
    //  递归获取该id的所有父id，不含该id
    getParentIdsById (arrs,id) {
      let parentIds = []
      function findParentIds (arr, id) {
        for (let i = 0; i < arr.length; i++) {
          let e = arr[i]
          if (e.id == id && e.parentId) {
            parentIds.push(e.parentId)
            //从头再找父id的上级
            findParentIds(arrs, e.parentId)
          }
          if (e.childOrganizations && e.childOrganizations.length > 0) {
            findParentIds(e.childOrganizations, id)
          }
        }
        return parentIds
      }
      findParentIds(arrs, id)
      return parentIds
    },
    getPopupContainer () {
      return document.body
    },
    changeRole (val) {
      this.formData.roleIds = val
      this.$refs.formComp.validateField('roleIds')
    },
    // 获取表单中的数据
    getFormData () {
      return new Promise((resolve, reject) => {
        const data = this.formData
        this.$refs.formComp.validate(valid => {
          if (!valid) {
            reject(valid)
          }
          // data.organizationId = data.organizationIds[data.organizationIds.length - 1]
          delete data.organizationIds
          resolve(data)
        })
      })
    },
    resetFormData () {
      this.$refs.formComp && this.$refs.formComp.resetFields()
    }
  }
}
</script>
